package com.thingple.app.io;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;

import com.thingple.settings.AppConst;
import com.thingple.settings.Common;
import com.thingple.shared_context.SharedContext;

public class MainActivity extends com.thingple.web.WebViewActivity {

    private boolean longPress = false;
    private int configKeyCode = KeyEvent.KEYCODE_BACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected WebView getWebView() {
        return (WebView) findViewById(R.id.home_web_view);
    }

    @Override
    protected Uri url() {
        String urlPrefix = SharedContext.shareInstance().get(AppConst.PAGE, null);
        String path = "home.html";
        return Common.parseUrl(urlPrefix, path);
    }

    @Override
    protected int viewId() {
        return R.layout.activity_main;
    }

    public void init() {
        App.instance.versionControllHandler.update();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == configKeyCode) {
            if (longPress) {
                longPress = false;
                return true;
            }
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {// main activity不退出
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    public void openConfigActivity(View view) {

        view.setVisibility(View.INVISIBLE);
        Intent intent = new Intent();
        intent.setClass(this, ConfigActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == configKeyCode) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {

                if (event.getRepeatCount() == 0) {
                    event.startTracking();
                    longPress = false;
                } else {
                    longPress = true;
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == configKeyCode) {
            ImageView btn = (ImageView) findViewById(R.id.btn_config);
            if (btn.getVisibility() == View.INVISIBLE) {
                btn.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

}
